package util;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Date;

import javax.swing.*;
import javax.swing.text.BadLocationException;

public class ConsoleUI extends JFrame {
	
	private ConsoleInputHandler consoleInputHandler = new ConsoleInputHandler();
	private JScrollPane outputScroll = new JScrollPane();
    private JTextArea output = new JTextArea();
    private JTextField input = new JTextField();
    private int height = 400;
    private int width  = 600;
    
	public ConsoleUI(String title, ConsoleInputHandler console){
		this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
		consoleInputHandler = console;
		
		// Add a keylistener to the input field, so the user can submit with enter instead of a button
        input.addKeyListener(new ProcessInput());

        // layout the console
        output.setLineWrap(true);
        output.setWrapStyleWord(true);
        output.setEditable(false);
        output.transferFocus();
        output.setFont(new Font("monospaced",Font.PLAIN,15));

        outputScroll.setViewportView(output);
        
        this.setLayout(new BorderLayout());
        add(outputScroll,BorderLayout.CENTER);
        add(input,BorderLayout.SOUTH);

        this.setTitle(title);
        
        Point windowPos = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        
        windowPos.translate(-1*width/2, -1*height/2);
        
        this.setSize( width, height);
        this.setLocation(windowPos);
        
        this.setVisible(true);
        
        input.requestFocus();
	}

    public void println(String str){
        // truncating - anti memory-hog.
        if (output.getLineCount() > 300){
            try {
                output.replaceRange("", 0, output.getLineStartOffset(20));
            } catch (BadLocationException ex) {}
        }
        // append the new text and scroll to the bottom
        
        output.append(str + '\n');
        
        // The below event is simply a ctrl + end keystroke. 
        KeyEvent e = new KeyEvent(output, KeyEvent.KEY_PRESSED, 0, KeyEvent.CTRL_DOWN_MASK, KeyEvent.VK_END, KeyEvent.CHAR_UNDEFINED);
        // When ctrl+end is passed to the textarea, it scrolls to the bottom.
        outputScroll.dispatchEvent(e);
    }
    
    private class ProcessInput implements KeyListener {
    	public ProcessInput() {}
    	

		@Override
		public void keyReleased(KeyEvent e) {
			 if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				 
				 consoleInputHandler.processConsoleInput(input.getText());
				 input.setText("");
				 
			 }
			
		}

		// next two is not used
		@Override
		public void keyPressed(KeyEvent e) {}
		
		@Override
		public void keyTyped(KeyEvent e) {}
    	
    }
	

}
